﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Common;
using log4net;
using SqlSugar;
using AutoFacUtils;
using CashFlow.ShopManage.Def;
using CashFlow.Db.DAL;
using CashFlow.Db.Entity;
using CashFlow.Db.Repository;
using CashFlow.ShopManage.Service;

namespace CashFlow.ShopManage.Service.Implement
{
    public class ShopUserService : Service<ShopUserEntity>, IShopUserService
    {
        public IList<UserInfoAndReferenceUserInfo> QueryShopAllUsersByShopManagerUserId(
            int shopManagerUserId)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                var ls = db.Queryable<ShopUserEntity>()
                           .InnerJoin<UserInfoEntity>((su, u1) => su.UserId == u1.Id)
                           .InnerJoin<UserInfoEntity>((su, u1, u2) => u1.ReferenceInvitationCode == u2.InvitationCode)
                           .Where((su, u1, u2) => su.ShopManagerUserId == shopManagerUserId)
                           .Select((su, u1, u2) => new UserInfoAndReferenceUserInfo
                           {
                               UserInfo = u1,
                               ReferenceUserInfo = u2
                           })
                           .ToList();
                return ls;
            }
        }

        public IList<int> QueryShopAllUserIdsByShopManagerUserId(int shopManagerUserId)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                var ls = db.Queryable<ShopUserEntity>()
                           .Where(x => x.ShopManagerUserId == shopManagerUserId)
                           .Select(x => x.UserId)
                           .ToList();
                return ls;
            }
        }

        public bool IsUserBelongsShop(int userId, int shopManagerUserId)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                int n = db.Queryable<ShopUserEntity>()
                          .Where(x => x.UserId == userId
                            && x.ShopManagerUserId == shopManagerUserId)
                          .Count();
                return n > 0;
            }
        }
    }
}